package top.zhangjianyong.tools.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.json.JsonMapper;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Optional;

/**
 * @author ： zhangjianyong
 * @date ： 2021/11/1 14:39
 */
public class SessionUtil {

    private static HttpSession getSession() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null)
            return null;
        HttpServletRequest request = requestAttributes.getRequest();
        return request.getSession();
    }


    public static void setForTable(Object o) throws Exception {
        Class<?> aClass = o.getClass();
        TableName annotation = aClass.getAnnotation(TableName.class);
        String name = annotation.value();
        Optional.ofNullable(getSession())
                .orElseThrow(() -> new Exception("获取session异常"))
                .setAttribute(name, o);
    }

    public static <T> T getForTable(Class<T> aClass) throws Exception {
        TableName annotation = aClass.getAnnotation(TableName.class);
        String name = annotation.value();
        Object o = Optional.ofNullable(getSession())
                .orElseThrow(() -> new Exception("获取session异常"))
                .getAttribute(name);
        if (o == null)
            return null;

        if (o.getClass().equals(aClass)) {
            return JSON.parseObject(JSONObject.toJSONString(o), aClass);
        }
        throw new Exception("类型转换异常");
    }

}
